<?php
declare(strict_types=1);

namespace WebApp\lib\encrypt;

/**
 * [AesSecurity aes加密，支持PHP7.1]
 */
class Aes
{
    /**
     * [encrypt aes加密]
     * @param $input
     * @param $key
     * @param string $mode
     * @return string [type]                          [加密后的数据]
     * @internal param $ [type]                   $input [要加密的数据]
     * @internal param $ [type]                   $key   [加密key]
     */
    public static function encrypt($input, $key, $mode='ECB')
    {
        $data = openssl_encrypt($input, "AES-128-$mode", $key, OPENSSL_RAW_DATA);
        return $data;
    }

    /**
     * [decrypt aes解密]
     * @param $sStr
     * @param $sKey
     * @param string $mode
     * @return string [type]                         [解密后的数据]
     * @internal param $ [type]                   $sStr [要解密的数据]
     * @internal param $ [type]                   $sKey [加密key]
     */
    public static function decrypt($sStr, $sKey, $mode='ECB')
    {
        $decrypted = openssl_decrypt($sStr, "AES-128-$mode", $sKey, OPENSSL_RAW_DATA);
        return $decrypted;
    }

    /**
     * @param $ciphertext_dec
     * @param null $key
     * @return string
     */
    public static function AesDecrypt($ciphertext_dec, $key = null)
    {
        if ($ciphertext_dec == '') return '';
//        $ciphertext_dec = base64_decode($ciphertext_dec);
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $key=substr($key, 0, mcrypt_enc_get_key_size($module));

        $iv = str_repeat("\0", 16);    //解密的初始化向量要和加密时一样。
        /* Initialize encryption module for decryption */
        mcrypt_generic_init($module, $key, $iv);


        /* Decrypt encrypted string */
        $decrypted = mdecrypt_generic($module, $ciphertext_dec);


        /* Terminate decryption handle and close module */
        mcrypt_generic_deinit($module);
        mcrypt_module_close($module);
        $a = rtrim($decrypted,"\0");
        return $a;
    }
}